package com.treasure.mall.zbqmallapi.controller.integral;

import com.treasure.mall.biz.dto.condition.integral.IntegralOrderCondition;
import com.treasure.mall.biz.dto.integral.IntegralOrderCreateDTO;
import com.treasure.mall.biz.entity.integral.IntegralOrderPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.service.core.integral.IntegralOrderService;
import com.treasure.mall.biz.vo.PageDataVO;
import com.treasure.mall.zbq.common.annotation.CurrentUser;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbqmallapi.vo.integral.OrderVO;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/8/25
 */
@RestController
@RequestMapping("/integral/order")
public class IntegralOrderController {
    @Resource
    private IntegralOrderService orderService;

    /**
     * 创建订单
     *
     * @param userPO
     * @param dto
     * @return
     */
    @PostMapping("/create")
    public ApiResult create(@CurrentUser UserPO userPO, @RequestBody IntegralOrderCreateDTO dto) {
        dto.setUserPO(userPO);
        IntegralOrderPO po = orderService.create(dto);

        return ApiResult.ok(new OrderVO(po));
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @GetMapping("/detail/{id}")
    public ApiResult detail(@PathVariable String id) {
        IntegralOrderPO po = orderService.findById(id);

        return ApiResult.ok(new OrderVO(po));
    }

    /**
     * 用户订单列表
     *
     * @param userPO
     * @param condition
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public ApiResult list(
            @CurrentUser UserPO userPO,
            IntegralOrderCondition condition,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "") int size
    ) {
        condition.setUserId(userPO.getUserId());
        Page<IntegralOrderPO> pages = orderService.findAll(page, size, condition);

        PageDataVO<OrderVO> pageDataVO = new PageDataVO<>();
        pageDataVO.setPageCount(pages.getTotalPages());
        pageDataVO.setPageIndex(page);
        pageDataVO.setPageSize(size);
        pageDataVO.setTotal(pages.getTotalElements());

        List<OrderVO> vos = pages.getContent().stream().map(OrderVO::new).collect(Collectors.toList());
        pageDataVO.setRows(vos);

        return ApiResult.ok(pageDataVO);
    }
}
